﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;

namespace Service
{
    public class SubService
    {
        readonly ConnectionMultiplexer redisConnection;
        string tcp = "127.0.0.1:6379";
        readonly ISubscriber subscriber;

        /// <summary>
        /// 初始化订阅服务
        /// </summary>
        /// <param name="tcpOrIp"></param>
        public SubService(string tcpOrIp = null)
        {
            tcp = tcpOrIp ?? tcp;
            redisConnection = ConnectionMultiplexer.Connect(tcp);
            subscriber = redisConnection.GetSubscriber();
        }

        /// <summary>
        /// 订阅频道
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="OnMessage"></param>
        public void Subscrib(string channel, Action<RedisChannel, RedisValue> OnMessage = null)
        {
            if (!string.IsNullOrEmpty(channel) && OnMessage != null)
            {
                OnMessage = OnMessage ?? ((channels, message) =>
                {
                    Console.WriteLine((string)message);
                });
                subscriber.Subscribe(channel, OnMessage);
            }
        }



    }
}
